package com.workerhelping.controller;

import com.workerhelping.config.ShortMessageProperties;
import com.workerhelping.dto.PhoneNumDTO;
import com.workerhelping.constant.ConstantEnum;
import com.workerhelping.dto.WorkerIdDTO;
import com.workerhelping.elasticsearchEntity.ESAssistVO;
import com.workerhelping.feignClients.ESFeignClient;
import com.workerhelping.feignClients.MySQLFeignClient;
import com.workerhelping.feignClients.RedisFeignClient;
import com.workerhelping.po.Confirm;
import com.workerhelping.po.Notice;
import com.workerhelping.po.Worker;
import com.workerhelping.result.Result;
import com.workerhelping.result.ResultCodeEnum;
import com.workerhelping.utils.MD5Util;
import com.workerhelping.utils.SendMessageUtil;
import com.workerhelping.vo.LoginVo;
import com.workerhelping.vo.ModifyPswdVO;
import com.workerhelping.vo.RegisterVO;
import com.workerhelping.vo.WorkerConfirmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

//@CrossOrigin(allowCredentials = "true")
@Slf4j
@RestController
@RequestMapping("/worker")
public class WorkerController {

    @Autowired
    ShortMessageProperties shortMessageProperties;

    @Autowired
    private RedisFeignClient redisFeignClient;

    @Autowired
    private MySQLFeignClient mySQLFeignClient;

    @Autowired
    private ESFeignClient esFeignClient;

    /**
     * 发送验证码
     *
     * @param phoneNumber
     * @return
     */
    @GetMapping("/sendMessage/{phone}")
    public Result<Object> sendMessage(@PathVariable("phone") String phoneNumber) {
        try {
            Result<String> result = SendMessageUtil.sendShortMessage(
                    shortMessageProperties.getHost(),
                    shortMessageProperties.getPath(),
                    shortMessageProperties.getMethod(),
                    phoneNumber,
                    shortMessageProperties.getAppCode(),
                    shortMessageProperties.getSmsSignId(),
                    shortMessageProperties.getTemplateId());
            String code = result.getData();
            Result<Object> res = redisFeignClient.sendMessage(phoneNumber, code);
            if (!StringUtils.isEmpty(code) && res.getMessage().equals(ResultCodeEnum.SUCCESS.getMessage()))
                return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.build(null, ResultCodeEnum.REGISTER_CODE_SEND_ERROR);
        }
        return Result.ok();
    }

    /**
     * 注册
     *
     * @param registerVO
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterVO registerVO) {
        PhoneNumDTO phoneNumDTO = new PhoneNumDTO();
        BeanUtils.copyProperties(registerVO, phoneNumDTO);
        Result<String> getResult = redisFeignClient.getVerificationCode(phoneNumDTO);
        if (getResult.getCode() != 200)
            return getResult;
        Worker worker = new Worker();
        BeanUtils.copyProperties(registerVO, worker);
        worker.setPassword(MD5Util.encode(worker.getPassword()));
        Result<String> result = mySQLFeignClient.saveWorker(worker);
        if (result.getCode().equals(ResultCodeEnum.FAIL.getCode()))
            return Result.build(null, ResultCodeEnum.REGISTER_PHONENUM_NOT_UNIQUE);
        return Result.ok();
    }

    /**
     * 职工登录
     *
     * @param loginVo
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginVo loginVo, HttpSession session) {
        PhoneNumDTO phoneNumDTO = new PhoneNumDTO(loginVo.getPhoneNumber());
        Result<Worker> result = mySQLFeignClient.getWorkerByPhoneNum(phoneNumDTO);
        if (result.getCode().equals(ResultCodeEnum.FAIL.getCode()))
            return Result.build(null, ResultCodeEnum.LOGIN_FAIL);
        Worker worker = result.getData();
        String curPswd = MD5Util.encode(loginVo.getPassword());
        String sourcePswd = worker.getPassword();
        if (!curPswd.equals(sourcePswd))
            return Result.build(null, ResultCodeEnum.LOGIN_FAIL);
        session.setAttribute(ConstantEnum.ID.getMsg(), worker.getId());
        return Result.ok();
    }

    /**
     * 注销
     *
     * @param session
     */
    @Deprecated
    @GetMapping("/logout")
    public void logout(HttpSession session) {
        Object workerIdObj = session.getAttribute(ConstantEnum.ID.getMsg());
        int workerId = Integer.parseInt(workerIdObj.toString());
        WorkerIdDTO workerInfoDTO = new WorkerIdDTO(workerId);
        //逻辑删除
        mySQLFeignClient.updateConfirmStatusByWorkerId(workerInfoDTO);
        session.invalidate();
    }

    /**
     * 获取政策信息
     *
     * @return
     */
    @GetMapping("/notice")
    public Result<List<Notice>> search() {
        Result<List<Notice>> result = mySQLFeignClient.search();
        if (!result.isOk())
            return Result.build(null, ResultCodeEnum.DATA_IS_EMPTY);
        List<Notice> notices = result.getData();
        if (notices.isEmpty())
            return Result.build(null, ResultCodeEnum.DATA_IS_EMPTY);
        return Result.ok(notices);
    }


    /**
     * 根据id查看政策
     *
     * @param id
     * @return
     */
    @GetMapping("/notice/preview/{id}")
    public Result<Notice> preview(@PathVariable("id") Integer id) {
        Result<Notice> getResult = mySQLFeignClient.getNoticeById(id);
        Notice notice = getResult.getData();
        if (!getResult.isOk())
            return Result.fail();
        return Result.ok(notice);
    }

    /**
     * 接收管理员消息
     *
     * @param session
     * @return
     */
    @GetMapping("/workerConfirm")
    public Result<List<WorkerConfirmVO>> workerConfirm(HttpSession session) {
        Object workerId = session.getAttribute(ConstantEnum.ID.getMsg());
        WorkerIdDTO workerIdDTO = new WorkerIdDTO(Integer.parseInt(workerId.toString()));
        Result<List<Confirm>> confirmResult = mySQLFeignClient.getConfirmByWorkerId(workerIdDTO);
        if (!confirmResult.isOk())
            return Result.fail();
        List<Confirm> confirms = confirmResult.getData();
        ArrayList<WorkerConfirmVO> list = new ArrayList<>();
        for (Confirm confirm : confirms) {
            WorkerConfirmVO workerConfirmVO = new WorkerConfirmVO();
            BeanUtils.copyProperties(confirm, workerConfirmVO);
            list.add(workerConfirmVO);
        }
        if (confirms.size() == 0)
            return Result.build(null, ResultCodeEnum.CONFIRM_IS_EMPTY);
        return Result.ok(list);
    }


    /**
     * 消息设置为已读
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteConfirm(@PathVariable("id") Integer id) {
        Result<String> deleteRest = mySQLFeignClient.deleteConfirmById(id);
        if (!deleteRest.isOk())
            return Result.fail();
        return Result.ok();
    }


    /**
     * 查看我的补助信息
     * @param startDate
     * @param endDate
     * @param minPrice
     * @param maxPrice
     * @param category
     * @param session
     * @return
     */
    @GetMapping("/assist")
    public Result<List<ESAssistVO>> searchAssist(@RequestParam(value = "startDate", required = false) String startDate,
                                                 @RequestParam(value = "endDate", required = false) String endDate,
                                                 @RequestParam(value = "minPrice", required = false) Double minPrice,
                                                 @RequestParam(value = "maxPrice", required = false) Double maxPrice,
                                                 @RequestParam(value = "sCategory", required = false) String category,
                                                 HttpSession session) {
        int workerId = Integer.parseInt(session.getAttribute(ConstantEnum.ID.getMsg()).toString());
        Result<List<ESAssistVO>> result = esFeignClient.searchAssist(startDate, endDate, minPrice, maxPrice, category, workerId);
        if (!result.isOk())
            return Result.fail();
        List<ESAssistVO> assists = result.getData();
        if (assists.isEmpty())
            return Result.build(null, ResultCodeEnum.DATA_IS_EMPTY);
        return Result.ok(assists);
    }

    /**
     * 找回密码
     * 表单验证：
     * 1. 确认密码与原密码
     * 2. 旧密码与新密码不得一致
     * @return
     */
    @PostMapping("/modifyPswd")
    public Result<String> modifyPswd(@RequestBody ModifyPswdVO modifyPswdVO ,HttpSession session) {
        int workerId = Integer.parseInt(session.getAttribute(ConstantEnum.ID.getMsg()).toString());
        PhoneNumDTO phoneNumDTO = new PhoneNumDTO(modifyPswdVO.getPhoneNumber());
        Result<Worker> getResult = mySQLFeignClient.getWorkerByPhoneNum(phoneNumDTO);
        if (!getResult.isOk())
            return Result.fail();
        Result<String> codeResult = redisFeignClient.getVerificationCode(phoneNumDTO);
        if (codeResult.getCode() != 200)
            return codeResult;
        String code = codeResult.getData();
        if (!code.equals(modifyPswdVO.getCode()))
            return Result.build(null, ResultCodeEnum.REGISTER_CODE_ERROR);
        Worker worker = getResult.getData();
        worker.setId(workerId);
        String sourcePswd = worker.getPassword();
        String oldPswd = modifyPswdVO.getOldPswd();
        String newPswd = modifyPswdVO.getNewPswd();
        if (!sourcePswd.equals(MD5Util.encode(oldPswd)))
            return Result.build(null, ResultCodeEnum.OLD_PASSWORD_ERROR);
        String encodedNewPswd = MD5Util.encode(newPswd);
        worker.setPassword(encodedNewPswd);
        Result<String > updateResult = mySQLFeignClient.updateWorkerPswd(worker);
        if (!updateResult.isOk())
            return Result.fail();
        return Result.ok();
    }

}
